#!/usr/bin/python3
# -*- coding: utf-8 -*-
#======================================#
# @Author   : duanqizhong
# @time     : 2022-8-7 18:05
# @file     : modify_branch
# @Software : PyCharm
#======================================#


import os
import threading
import time
import xml.etree.ElementTree as ET

import argparse
from jenkinsapi.jenkins import Jenkins


class JenkinsOP:
    _instance_lock = threading.Lock()

    def __init__(self, url, username, password):
        self.url = url
        self.name = username
        self.password = password
        self.jenkins = Jenkins(url, username=username, password=password)

    def __new__(cls, url, username, password):
        if not hasattr(cls, '_instance'):
            with JenkinsOP._instance_lock:
                if not hasattr(cls, '_instance'):
                    JenkinsOP._instance = super().__new__(cls)
        return JenkinsOP._instance

    def get_jenkins_op(self):
        return self.jenkins

    def build_job(self, jobname):
        self.jenkins.build_job(jobname=jobname)

    def get_view_jobs_info(self, view_loc=None):
        jobs = {}
        if view_loc is None:
            jobs = self.jenkins.get_jobs()
            return jobs

        try:
            view = os.path.join(self.url, view_loc).replace('\\', '/')
            jobs = self.jenkins.get_jenkins_obj_from_url(view).get_jobs()
        except Exception as e:
            return jobs
        return jobs

    def update_config_by_tag(self, job, childEL, content, parentEL=None):
        config = job[1].get_config()
        root = ET.fromstring(config)
        if parentEL is not None:
            for element in root.iter(tag=parentEL):
                for child in element.iter():
                    if child.tag == childEL:
                        # child.text = f"*/{content.strip()}"
                        child.text = content.strip()
                        # print("branch", child.text)
        else:
            # childEL不要存在重复，存在重复只修改第一个
            for child in root.iter(tag=childEL):
                child.text = content.strip()
                # print("branch",child.text)
                break

        config_list = ET.tostringlist(root, encoding="utf-8", method="xml")
        update_xml = ''
        for byte in config_list:
            update_xml = update_xml + byte.decode("utf-8")

        # 关闭jenkins csrf验证
        try:
            print(f"is updating: {job[0].split('/')[-1]}, set branch={content}")
            job[1].update_config(update_xml, full_response=False)
            print(f"update successful! branch={content}....")
        except Exception as e:
            print(f"ERROR:{str(e)}")
            raise (f"{job[0]} update failed!")


def run(env="wms-8080", branch="origin/release"):
    url = "http://10.4.95.198:8080"
    username = "wms"
    password = "111111"
    j = JenkinsOP(url, username, password)
    for job in j.get_view_jobs_info(f"view/{env}"):
        print(job[0], job[1].get_config_xml_url())
        j.update_config_by_tag(job, 'name', branch, "hudson.plugins.git.BranchSpec")
        time.sleep(2)
        jobname = os.path.basename(job[0])
        print(f"正在构建......{jobname}")
        j.build_job(jobname)
        print("\n")


def args_run():
    parse = argparse.ArgumentParser(description="modify branch and run!")
    parse.add_argument("env", type=str, default="8080")
    parse.add_argument("branch", type=str, default="release")
    args = parse.parse_args()
    env = args.env
    branch = args.branch
    run(env, branch)


if __name__ == '__main__':
    args_run()
    # run("wms-8080", "origin/sprint_20220628_6.3")
